package com.mjf.cjt.service.impl;

import com.chanjet.openapi.sdk.java.domain.GetAppAccessTokenContent;
import com.chanjet.openapi.sdk.java.domain.GetOrgAccessTokenContent;
import com.chanjet.openapi.sdk.java.domain.GetTokenByPermanentCodeContent;
import com.chanjet.openapi.sdk.java.exception.ChanjetApiException;
import com.chanjet.openapi.sdk.java.response.GetAppAccessTokenResponse;
import com.chanjet.openapi.sdk.java.response.GetOrgAccessTokenResponse;
import com.chanjet.openapi.sdk.java.response.GetTokenByPermanentCodeResponse;
import com.chanjet.openapi.sdk.java.response.GetTokenResponse;
import com.mjf.cjt.mapper.CjtAuthMapper;
import com.mjf.common.exception.ServiceException;
import com.mjf.cjt.config.OpenApiConfig;
import com.mjf.cjt.domain.PermanentAuthEntity;
import com.mjf.cjt.domain.TicketEntity;
import com.mjf.cjt.domain.TokenEntity;
import com.mjf.cjt.http.CjtHttpUtils;
import com.mjf.cjt.service.CjtAuthService;
import com.mjf.cjt.spi.ChanjetSpi;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

@Service
@Slf4j
public class CjtAuthServiceImpl implements CjtAuthService {

    public static final String COMPANY_TEMP_AUTH_CODE_URL = "/auth/orgTempAuthCode/resend";
    public static final String TOKEN_URL = "/auth/v2/getToken";

    @Autowired
    private CjtAuthMapper cjtAuthMapper;

    @Autowired
    private OpenApiConfig openApiConfig;

    @Autowired
    private ChanjetSpi chanjetSpi;

    @Autowired
    private CjtHttpUtils cjtHttpUtils;

    @Override
    public String getToken(String orgId) throws ChanjetApiException {
        //获取用户永久授权码；
        String userCode = cjtAuthMapper.getUserCode(orgId);
        if(userCode == null){
            log.error("此org未配置用户永久授权码,org:{}",orgId);
           throw new ServiceException("账套："+orgId+";未配置用户永久授权码,请到自主应用绑定，开通账套权限");
        }
        //获取公司永久授权码
        PermanentAuthEntity permanentAuthCode = cjtAuthMapper.getPermanentAuthCode(orgId);
        if(permanentAuthCode == null){
            //获取应用凭证
            //立即触发企业临时授权码推送
            chanjetSpi.sendTempCode(orgId);
            log.error("此org未配置公司永久授权码,org:{}",orgId);
            throw new ServiceException("账套："+orgId+";未配置公司永久授权码，已经发送授权申请，请再次点击操作");
        }
        //获取ticket
        TicketEntity ticketEntity = cjtAuthMapper.getTicket(openApiConfig.getAppKey());
        //获取应用凭证
        GetAppAccessTokenContent getAppAccessTokenContent = new GetAppAccessTokenContent();
        getAppAccessTokenContent.setAppTicket(ticketEntity.getTicket());
        GetAppAccessTokenResponse appAccessToken = chanjetSpi.getAppAccessToken(getAppAccessTokenContent);
        //如果应用凭证没有获取成功，说明是ticket过期了，立即发送ticket
        if(!"200".equals(appAccessToken.getCode())){
            log.error("ticket过期，立即发送ticket");
            chanjetSpi.sendTicket();
            throw new ServiceException("ticket过期，立即发送ticket");
        }else{
            log.info("获取应用凭证成功:{}",appAccessToken.getResult().getAppAccessToken());
        }

        //获取企业凭证
        GetOrgAccessTokenContent getOrgAccessTokenContent = new GetOrgAccessTokenContent();
        getOrgAccessTokenContent.setAppAccessToken(appAccessToken.getResult().getAppAccessToken());
        getOrgAccessTokenContent.setPermanentAuthCode(permanentAuthCode.getPermanentAuthCode());

        GetOrgAccessTokenResponse orgAccessToken = chanjetSpi.getOrgAccessToken(getOrgAccessTokenContent);
        if(!"200".equals(orgAccessToken.getCode())){
            log.error("获取企业凭证失败");
            throw new RuntimeException("获取企业凭证失败" + orgId);
        }else{
            log.info("获取企业凭证成功:{}",orgAccessToken.getResult().getOrgAccessToken());
        }

        //通过企业凭证获取token
        GetTokenByPermanentCodeContent getTokenByPermanentCodeContent = new GetTokenByPermanentCodeContent();
        getTokenByPermanentCodeContent.setUserAuthPermanentCode(userCode);
        getTokenByPermanentCodeContent.setOrgAccessToken(orgAccessToken.getResult().getOrgAccessToken());
        GetTokenByPermanentCodeResponse tokenByPermanentCode = chanjetSpi.getTokenByPermanentCode(getTokenByPermanentCodeContent);
        if(!"200".equals(tokenByPermanentCode.getCode())){
            log.error("获取token失败");
            throw new RuntimeException("获取token失败"+orgId);
        }else{
            log.info("获取token成功:{}",tokenByPermanentCode.getResult().getAccessToken());
            log.info("用户永久授权码：{}",tokenByPermanentCode.getResult().getUserAuthPermanentCode());
            TokenEntity token = new TokenEntity();
            token.setAccessToken(tokenByPermanentCode.getResult().getAccessToken());
            token.setOrgId(orgId);
            cjtAuthMapper.saveToken(token);
        }

        return tokenByPermanentCode.getResult().getAccessToken();

    }


    @Override
    public String doCompanyTempAuth(String appName, String orgId) {
        String path = "appName="+appName+"&orgId="+orgId;
        return cjtHttpUtils.doGet(COMPANY_TEMP_AUTH_CODE_URL,path);
    }

    @Override
    public void doTokenByTempCode(String code)  {
        try{
            GetTokenResponse resultToken = chanjetSpi.getToken(code, openApiConfig.getRedirectUri());
            if(resultToken != null && resultToken.getResult() != null){
                cjtAuthMapper.saveUserPermanentCode(resultToken.getResult().getUserAuthPermanentCode(),resultToken.getResult().getOrgId());

            }
        }catch (Exception e){
            log.error(e.getMessage());
        }

    }
}

